package com.flk.oauth.service.impl;

import com.flk.oauth.entity.OauthUser;
import com.flk.oauth.repository.OauthUserRepository;
import com.flk.oauth.service.IOauthUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @author xxwy
 * on 2018/10/15 0015
 */
@Service
public class OauthUserServiceImpl implements IOauthUserService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    @Autowired
    private OauthUserRepository oauthUserRepository;


    @Override
    @Transactional
    public OauthUser insertOauthUser(OauthUser oauthUser) {
        if (oauthUser != null) {
            validateUserInfo(oauthUser);
            String hash = encoder.encode(oauthUser.getPassword());
            oauthUser.setPassword(hash);
            log.info("new user has been created: {}", oauthUser.getUsername());
            OauthUser save = oauthUserRepository.save(oauthUser);
            return save;
        }
        return null;
    }

    @Override
    @Transactional
    public void bolckUser(String phone) {
        OauthUser byPhone = oauthUserRepository.findByPhone(phone);
        if (byPhone != null) {
            oauthUserRepository.updateUserBolck(byPhone.getId());
        }
    }

    private void validateUserInfo(OauthUser oauthUser){
        if(oauthUser.getPhone()!=null){
            OauthUser byPhone = oauthUserRepository.findByPhone(oauthUser.getPhone());
            Assert.isNull(byPhone, "user already exists: " +oauthUser.getPhone());
        }
        if(oauthUser.getUsername()!=null) {
            OauthUser byUsername = oauthUserRepository.findByUsername(oauthUser.getUsername());
            Assert.isNull(byUsername, "user already exists: " + oauthUser.getUsername());
        }
    }


}